using System;
using System.Collections;
using System.ComponentModel;
using System.Web;

namespace WCPierce.Web.UI
{
    /// <summary>
    /// Thank you M$.
    /// </summary>
    internal sealed class DataSourceHelper
    {
        private DataSourceHelper() { }


        internal static IEnumerable GetResolvedDataSource(object dataSource, string dataMember)
        {
            if (dataSource != null)
            {
                IListSource source1 = dataSource as IListSource;
                if (source1 != null)
                {
                    IList list1 = source1.GetList();
                    if (!source1.ContainsListCollection)
                    {
                        return list1;
                    }
                    if ((list1 != null) && (list1 is ITypedList))
                    {
                        ITypedList list2 = (ITypedList)list1;
                        PropertyDescriptorCollection collection1 = list2.GetItemProperties(new PropertyDescriptor[0]);
                        if ((collection1 == null) || (collection1.Count == 0))
                        {
                            throw new HttpException("ListSource_Without_DataMembers");
                        }
                        PropertyDescriptor descriptor1 = null;
                        if ((dataMember == null) || (dataMember.Length == 0))
                        {
                            descriptor1 = collection1[0];
                        }
                        else
                        {
                            descriptor1 = collection1.Find(dataMember, true);
                        }
                        if (descriptor1 != null)
                        {
                            object obj1 = list1[0];
                            object obj2 = descriptor1.GetValue(obj1);
                            if ((obj2 != null) && (obj2 is IEnumerable))
                            {
                                return (IEnumerable)obj2;
                            }
                        }
                        throw new HttpException("ListSource_Missing_DataMember: " + dataMember);
                    }
                }
                if (dataSource is IEnumerable)
                {
                    return (IEnumerable)dataSource;
                }
            }
            return null;
        }
    }
}
